package top.malaoshi.web.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class ResponseUtils {
    /**
     * 向客户度输出字符串
     * @param response
     * @param content
     * @throws IOException
     */
    public static void print(HttpServletResponse response,String content) throws IOException {
        // 一定要在获取流之前调用，否则无效
//        response.setContentType("text/html; charset=UTF-8");
//        response.setCharacterEncoding("UTF-8"); // 有时不写也可以
        PrintWriter out=response.getWriter();
        out.print(content);
        out.flush();// 在springboot、springmvc中，必须加此行代码，否则可能报错
        out.close();
    }
    /**
     * 向前端输出JSON字符串
     * @param response
     * @param json
     * @throws IOException
     */
    public static void sendJSON(HttpServletResponse response,String json) throws IOException {
        sendJSON(response, 200,json);
    }

    /**
     * 向前端输出JSON字符串
     * @param response
     * @param status 状态码
     * @param json
     * @throws IOException
     */
    public static void sendJSON(HttpServletResponse response,int status,String json) throws IOException {
        response.setStatus(status);
        // 一定要在获取流之前调用，否则无效
        String encoding = response.getCharacterEncoding();
//        System.out.println("encoding："+encoding);
        response.setContentType("application/json; charset="+encoding);
        //response.setCharacterEncoding("UTF-8"); // 有时不写也可以
        PrintWriter out=response.getWriter();
        out.write(json);
        out.flush();// 在springboot、springmvc中，必须加此行代码，否则可能报错
        out.close();
    }
    public static void sendJSON(HttpServletResponse response,int status,Object obj) throws IOException {
        // 调用 jackson，将javabean转换成json字符串
        ObjectMapper om=new ObjectMapper();
        String json=om.writeValueAsString(obj);
        sendJSON(response,status,json);
    }
    public static void sendJSON(HttpServletResponse response,Object obj) throws IOException {
        // 调用 jackson，将javabean转换成json字符串
        ObjectMapper om=new ObjectMapper();
        String json=om.writeValueAsString(obj);
        sendJSON(response,json);
    }

    public static void print500(HttpServletResponse response,String content) throws IOException {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        PrintWriter out=response.getWriter();
        out.print(content);
        flushAndClose(out);
    }
    private static void flushAndClose(PrintWriter out){
        out.flush();// 在springboot、springmvc中，必须加此行代码，否则可能报错
        out.close();
    }
}